//
// Created by 11510 on 2025/10/3.
//
#include "XMLAuxiliary.h"
std::string xml_auxiliary::trim(std::string s) {
    auto is_space = [](char c){
        return std::isspace(static_cast<unsigned char>(c));
    };

    while (!s.empty() && is_space(s.front()))
        s.erase(s.begin());
    while (!s.empty() && is_space(s.back()))
        s.pop_back();
    return s;
}

bool xml_auxiliary::parseAddress(const std::string& text, uint16_t& out) {
    if (text.empty())
        return false;
    std::string s = trim(text);
    try {
        unsigned long v = 0;
        if (s.size() > 1 && (s[0]=='0') && (s[1]=='x' || s[1]=='X')) {
            v = std::stoul(s.substr(2), nullptr, 16);
        } else {
            // if contains hex letters, parse hex; else parse decimal
            bool hasHexLetter = false;
            for (char c : s) {
                if ((c>='a' && c<='f') || (c>='A' && c<='F')) {
                    hasHexLetter = true;
                    break;
                }
            }
            if (hasHexLetter)
                v = std::stoul(s, nullptr, 16);
            else
                v = std::stoul(s, nullptr, 10);
        }
        if (v > 0xFFFF)
            return false;
        out = static_cast<uint16_t>(v);
        return true;
    } catch (...) {
        return false;
    }
}
uint64_t xml_auxiliary::fnv1a64(const std::string& s) {
    const uint64_t FNV_OFFSET_BASIS = 14695981039346656037ULL;
    const uint64_t FNV_PRIME = 1099511628211ULL;
    uint64_t hash = FNV_OFFSET_BASIS;
    for (unsigned char c : s) {
        hash ^= static_cast<uint64_t>(c);
        hash *= FNV_PRIME;
    }
    return hash;
}





